package fr.inria.phoenix.scenario.bwsnfirefighting.impl.controller;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;

import fr.inria.diagen.core.ServiceConfiguration;
import fr.inria.phoenix.scenario.bwsnfirefighting.framework.datatype.DangerLevel;
import fr.inria.phoenix.scenario.bwsnfirefighting.framework.datatype.DeviceStatus;
import fr.inria.phoenix.scenario.bwsnfirefighting.framework.datatype.Location;
import fr.inria.phoenix.scenario.bwsnfirefighting.framework.distributed.messagemanager.MessageManager;

public class MessageManagerImpl extends MessageManager {
	
	private String noRealTimeMessageLog = "noRealTimeMessages.log";
	private String SoftRealTimeMessageLog = "noRealTimeMessages.log";
	private String HardRealTimeMessageLog = "noRealTimeMessages.log";
	
	public MessageManagerImpl(ServiceConfiguration serviceConfiguration) {
		super(serviceConfiguration);
	}

	@Override
	public void onNewAlertDetection(DangerLevel newAlertDetectionValue,
			Location location) {
		SimpleDateFormat formatter=  new SimpleDateFormat("yyyy/MMM/dd HH:mm:ss");
		String logItem = formatter.format(Calendar.getInstance());
		logItem += "->Floor:" + location.getFloor() + " Room:" + location.getRoom();
		if (newAlertDetectionValue == DangerLevel.SAFE){
			logItem += " -> SAFE\n";
			sendNoRealTimeMessage(logItem);
		}
		else if (newAlertDetectionValue == DangerLevel.WARNING){
			logItem += " -> WARING\n";
			sendSoftRealTimeMessage(logItem);
		}
		else if (newAlertDetectionValue == DangerLevel.ALERT){
			logItem += " -> ALERT\n";
			sendHardRealTimeMessage(logItem);
		}
	}

	@Override
	public void onNewStatusDetection(DeviceStatus newStatusDetectionValue,
			Integer id) {
		SimpleDateFormat formatter=  new SimpleDateFormat("yyyy/MMM/dd HH:mm:ss");
		String logItem = formatter.format(Calendar.getInstance()) + "->";
		if (newStatusDetectionValue == DeviceStatus.FAULT){
			logItem += "FAULT Device id " + id + "\n";
		}
		sendNoRealTimeMessage(logItem);
	}
	
	private void sendHardRealTimeMessage(String logItem) {
		try {
			FileWriter log = new FileWriter(noRealTimeMessageLog);
			BufferedWriter out = new BufferedWriter(log);
			out.write(logItem);
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private void sendSoftRealTimeMessage(String logItem) {
		try {
			FileWriter log = new FileWriter(SoftRealTimeMessageLog);
			BufferedWriter out = new BufferedWriter(log);
			out.write(logItem);
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}

	private void sendNoRealTimeMessage(String logItem) {
		try {
			FileWriter log = new FileWriter(HardRealTimeMessageLog);
			BufferedWriter out = new BufferedWriter(log);
			out.write(logItem);
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}

}
